// pages/order-list/order-list.js
import { orderApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { formatPrice, formatDate, ORDER_STATUS_TEXT } from '../../utils/format.js'
import { ORDER_STATUS } from '../../utils/constants.js'

const app = getApp()

Page({
  data: {
    loading: true,
    orders: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    statusFilter: null, // 状态筛选
    statusOptions: [
      { value: null, label: '全部' },
      { value: ORDER_STATUS.PENDING_PAYMENT, label: '待付款' },
      { value: ORDER_STATUS.PENDING_ACCEPT, label: '待接单' },
      { value: ORDER_STATUS.DELIVERING, label: '派送中' },
      { value: ORDER_STATUS.DELIVERED, label: '已送达' },
      { value: ORDER_STATUS.COMPLETED, label: '已完成' },
      { value: ORDER_STATUS.CANCELLED, label: '已取消' }
    ],
    showStatusFilter: false
  },

  onLoad() {
    this.loadOrders()
  },

  onShow() {
    // 每次显示时重新加载订单列表
    this.loadOrders(true)
  },

  onPullDownRefresh() {
    this.loadOrders(true)
  },

  onReachBottom() {
    if (this.data.hasMore) {
      this.loadOrders(false, this.data.currentPage + 1)
    }
  },

  // 加载订单列表
  async loadOrders(refresh = false, page = 1) {
    if (!checkLoginAndRedirect()) {
      this.setData({ loading: false })
      return
    }

    try {
      if (refresh) {
        this.setData({ loading: true })
      }
      
      const params = {
        page,
        pageSize: this.data.pageSize
      }
      
      if (this.data.statusFilter !== null) {
        params.status = this.data.statusFilter
      }
      
      const res = await orderApi.getHistory(params)
      
      if (res.code === 1) {
        const { records, total } = res.data
        const orders = refresh ? records : [...this.data.orders, ...records]
        const hasMore = orders.length < total
        
        this.setData({
          orders,
          currentPage: page,
          hasMore
        })
      }
    } catch (error) {
      console.error('加载订单列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 显示状态筛选器
  showStatusFilter() {
    this.setData({
      showStatusFilter: true
    })
  },

  // 选择状态筛选
  selectStatusFilter(e) {
    const { value, label } = e.currentTarget.dataset
    this.setData({
      statusFilter: value,
      showStatusFilter: false
    })
    
    // 重新加载订单列表
    this.loadOrders(true)
  },

  // 取消筛选器
  cancelStatusFilter() {
    this.setData({
      showStatusFilter: false
    })
  },

  // 跳转到订单详情
  goToOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${orderId}`
    })
  },

  // 取消订单
  async cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id
    const order = this.data.orders.find(item => item.id === orderId)
    
    if (!order) return
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '取消中...' })
            
            const cancelRes = await orderApi.cancel(orderId)
            
            if (cancelRes.code === 1) {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              // 重新加载订单列表
              this.loadOrders(true)
            } else {
              throw new Error(cancelRes.msg || '取消失败')
            }
          } catch (error) {
            console.error('取消订单失败:', error)
            wx.showToast({
              title: error.message || '取消失败',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 支付订单
  async payOrder(e) {
    const orderId = e.currentTarget.dataset.id
    const order = this.data.orders.find(item => item.id === orderId)
    
    if (!order) return
    
    try {
      wx.showLoading({ title: '支付中...' })
      
      const res = await orderApi.payment({
        orderNumber: order.number,
        payMethod: order.payMethod
      })
      
      if (res.code === 1) {
        // 调用微信支付
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.packageStr,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: () => {
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
            // 重新加载订单列表
            this.loadOrders(true)
          },
          fail: (error) => {
            console.error('支付失败:', error)
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
      } else {
        throw new Error(res.msg || '支付失败')
      }
    } catch (error) {
      console.error('支付订单失败:', error)
      wx.showToast({
        title: error.message || '支付失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 再来一单
  async repeatOrder(e) {
    const orderId = e.currentTarget.dataset.id
    
    try {
      wx.showLoading({ title: '处理中...' })
      
      const res = await orderApi.repetition(orderId)
      
      if (res.code === 1) {
        wx.showToast({
          title: '已加入购物车',
          icon: 'success'
        })
        
        // 跳转到购物车
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/cart/cart'
          })
        }, 1500)
      } else {
        throw new Error(res.msg || '操作失败')
      }
    } catch (error) {
      console.error('再来一单失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 格式化订单状态
  formatOrderStatus(status) {
    return ORDER_STATUS_TEXT[status] || '未知状态'
  },

  // 格式化时间
  formatTime(time) {
    return formatDate(time, 'MM-DD HH:mm')
  }
})